package com.ns.dcjh.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.upyun.library.exception.RespException;

import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtils {

    private static final long TIMEOUT = 30;
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static OkHttpClient client = new OkHttpClient();
    private static Handler handler = new Handler(Looper.getMainLooper());
    private static String TAG = "httpTAG";

    public static void post(Context context, String url, JSONObject jsonObject, final HttpCallback callback) throws IOException, RespException {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(TIMEOUT, TimeUnit.SECONDS);
        builder.readTimeout(TIMEOUT, TimeUnit.SECONDS);
        builder.writeTimeout(TIMEOUT, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        client = builder.build();
        String cookies = (String) SharedPreferencesUtils.getInstance(context).objectForKey("cookies", "");
        String httpCookie = "";
        if (cookies.contains(";")) {
            String[] cs = cookies.split(";");
            for (String cookie : cs) {
                httpCookie = cookie;
            }
        } else {
            httpCookie = cookies;
        }
        RequestBody body = RequestBody.create(JSON, jsonObject.toString());
        Request request = null;
        Log.i(TAG, "url====" + url);
        request = new Request.Builder()
                .header("Cookie", httpCookie)
                .url(url)
                .post(body).build();

        onStart(callback);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                onError(callback, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    onSuccess(callback, response.body().string());
                } else {
                    onError(callback, response.message());
                }
            }

        });
    }

    public static void uploadFile(Context context, String url, JSONObject jsonObject, final HttpCallback callback) {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(TIMEOUT, TimeUnit.SECONDS);
        builder.readTimeout(TIMEOUT, TimeUnit.SECONDS);
        builder.writeTimeout(TIMEOUT, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        client = builder.build();
        String cookies = (String) SharedPreferencesUtils.getInstance(context).objectForKey("cookies", "");
        String httpCookie = "";
        if (cookies.contains(";")) {
            String[] cs = cookies.split(";");
            for (String cookie : cs) {
                httpCookie = cookie;
            }
        } else {
            httpCookie = cookies;
        }
        RequestBody body = RequestBody.create(JSON, jsonObject.toString());
        Request request = null;
        Log.i(TAG, "url====" + url);
        request = new Request.Builder()
                .header("Cookie", httpCookie)
                .url(url)
                .post(body).build();

        onStart(callback);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                onError(callback, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    onSuccess(callback, response.body().string());
                } else {
                    onError(callback, response.message());
                }
            }

        });
    }

    private static void onStart(final HttpCallback callback) {
        if (null != callback) {
            handler.post(new Runnable() {
                public void run() {
                    // 需要在主线程的操作。
                    callback.onStart();
                }
            });
        }
    }

    private static void onSuccess(final HttpCallback callback, final String data) {
        //debug(data);
        Log.i(TAG,"response-->"+data);
        if (null != callback) {
            handler.post(new Runnable() {
                public void run() {
                    // 需要在主线程的操作。

                    callback.onSuccess(data);
                }
            });
        }
    }

    private static void onError(final HttpCallback callback,final String msg) {
        Log.i(TAG,"onError -->"+msg);
        if (null != callback) {
            handler.post(new Runnable() {
                public void run() {
                    // 需要在主线程的操作。
                    callback.onError( msg);
                }
            });
        }
    }
}
